package cn.wzy.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.wzy.common.CodeMsg;
import cn.wzy.common.Constant;
import cn.wzy.common.Result;
import cn.wzy.pojo.User;
import cn.wzy.service.UserService;
import cn.wzy.service.impl.UserServiceImpl;
import cn.wzy.utils.RespUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author nihaowzy
 * @date 2020/12/22 17:55
 * 用于上传图片使用的注解
 *
 */
@WebServlet("/user.do")
@MultipartConfig
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            String tag = req.getParameter("service");
            Method method = this.getClass().getDeclaredMethod(tag, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //用户输入的验证码
        String checkCode = req.getParameter("checkCode");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //校验验证码
        HttpSession session = req.getSession();
        //获取session中的验证码
        Object o = session.getAttribute(Constant.CHECK_CODE_KEY);
        //校验验证码
        if (o  == null || !o .toString().equals(checkCode)){
            //验证码失败时返回的数据
            Result result = new Result(CodeMsg.USER_NAME_PASSWORD_ERROR);
            RespUtil.write(resp,result);
            return;
        }
        //
        Result result = userService.queryUserByUsernameAndPassword(username, password);
        //userService 会返回两种Result 一个是 用户名或密码失败的Result 里面只有业务码和业务消息
        //另一个是 成功业务码 成功业务消息 和 从数据库中查询的数据
        if (result.getCode().equals(CodeMsg.SUCCESS.code)){
            //将数据库中查询的对象存取到session中
            session.setAttribute(Constant.CURRENT_USER_KEY, result.getData());
            //存入以后将 Result中的data置空
            result.setData(null);
        }
        //System.out.println(result);
        RespUtil.write(resp,result);
    }
    /**
     * 查询分页用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //页码
        String page = req.getParameter("page");
        //每页条数
        String limit = req.getParameter("limit");
        //模糊查询的参数
        //用户名
        String username = req.getParameter("username");
        //真实姓名
        String realname = req.getParameter("realname");
        //角色
        String role = req.getParameter("role");
        //是否离职
        String deleted = req.getParameter("deleted");

        Map<String ,String> map = new ConcurrentHashMap<>(10);
        if (StrUtil.isNotBlank(username)){
            map.put("username",username);
        }
        if (StrUtil.isNotBlank(realname)){
            map.put("realname",realname);
        }
        if (StrUtil.isNotBlank(role)){
            map.put("role",role);
        }
        if (StrUtil.isNotBlank(deleted)){
            map.put("deleted",deleted);
        }

        Result result = userService.queryPage(map, Integer.parseInt(page), Integer.parseInt(limit));

        RespUtil.write(resp,result);

    }

    /**
     * 重置密码请求
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void resetPwd(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String id = req.getParameter("id");
        Result result = userService.resetPassword(id);

        RespUtil.write(resp,result);
    }

    /**
     * 员工离职请求
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void deleted(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String id = req.getParameter("id");

        Result deleted = userService.deleted(id);
        RespUtil.write(resp,deleted);
    }

    /**
     * 新增用户请求
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String realname = req.getParameter("realname");
        String username = req.getParameter("username");
        String role = req.getParameter("role");

        Result result = userService.addUser(username, realname, Integer.parseInt(role));
        RespUtil.write(resp,result);
    }

    /**
     * 用户退出请求
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //删除session中的用户
        req.getSession().invalidate();
        //跳转到登录界面
        resp.sendRedirect("index.jsp");
    }

    /**
     * 查询用户请求
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void salesMan(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Result result = userService.queryUser();
        RespUtil.write(resp,result);
    }

    /**
     * 修改密码
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //用户输的密码
        String password = req.getParameter("password");
        //新密码
        String newPassword = req.getParameter("newPassword");


        //获取当前登录的用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(Constant.CURRENT_USER_KEY);
        //System.out.println("userId+++"+user.getId());
        //获取用户旧密码
        String oldPassword = user.getPassword();
        //判断用户输入密码和初始密码是一致
        if (!StrUtil.equals(password,oldPassword)){
            RespUtil.write(resp,new Result(CodeMsg.USER_PASSWORD_ERROR));
        }
        Result result = userService.updatePassword(user.getId(),newPassword);
        RespUtil.write(resp,result);
    }

    /**
     * 上传图片
     * 处理文件请求
     * servlet 3.0以后支持注解文件上传
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void uploadImg(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取文件上传的数据
        Part img = req.getPart("useImg");
        System.out.println("img:::"+img);
        //获取请求头的name属性
        String name = img.getName();
        //获取文件原始的名称
        String fileOriginName = this.getFileOriginName(img);
        //生成一个新的文件名称
        UUID uuid = UUID.randomUUID();
        //获取文件的后缀名
        String extName = FileUtil.extName(fileOriginName);
        //文件的新名称
        String fileNewName = uuid.toString() + "."+ extName;
        //两个路径
        // 1 物理路径 保存文件的磁盘路径
        // 2 网络路径 文件能够被网络访问的路径 数据中存放的是网络路径
        //物理路径:C:\Users\wzy\Pictures\lovewallpaper\05.jpg
        //网络路径: 127.0.0.1:8080/cms/imgs/05.jpg

        //网络路径用于存放到数据库中 相对路径
        String imgUrl = "imgs/"+fileNewName;
        //服务器中的物理路径 是在Tomcat服务器中webapps文件下面 文件项目中imgs文件的的图片路径
        String realPath = req.getServletContext().getRealPath("imgs");
        //文件保存在服务器中的路径中 也被成为绝对路径
        String fileAbsolutePath  = realPath+ File.separator+fileNewName;
        System.out.println(fileAbsolutePath);
        //将文件保存在服务器中的绝对路径
        img.write(fileAbsolutePath);
        //修改数据库中的use表中的图片URL
        User  user = (User) req.getSession().getAttribute(Constant.CURRENT_USER_KEY);
        Result result = userService.upLoadImg(user.getId(),imgUrl);
        if (result.getCode() .equals(CodeMsg.SUCCESS.code)){
            user.setImg(imgUrl);

        }
        RespUtil.write(resp,result);

    }

    /**
     * 获取文件的真实名称
     * @param part
     * @return
     */
    private String getFileOriginName(Part part){
        String header = part.getHeader("Content-Disposition");
        String[] headers = header.split(";");
        //获取文件的名称
        String fileName = headers[2].trim();
        int begin = fileName.indexOf("\"");
        int last = fileName.lastIndexOf("\"");
        //文件名称
        fileName = fileName.substring(begin+1, last);
        System.out.println(fileName);
        return fileName;

    }






}
